package com.shundr.truck;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.AreaGridActivity;
import com.shundr.common.adapter.ExpectedFlowAdapter;
import com.shundr.common.adapter.ExpectedFlowAdapter.DeleteListener;
import com.shundr.common.model.AreaInfo;
import com.shundr.common.util.JsonUtil;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.common.view.ListViewForScrollView;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.frame.service.ShundrService;
import com.shundr.frame.util.StringUtil;
import com.shundr.truck.http.UserTruckRequest;
import com.shundr.truck.model.TruckInfo;
import com.shundr.truck.view.DialogChoiceTruck;
import com.shundr.truck.view.DialogChoiceTruck.TruckChoiceListener;

/**
 * 发布空车
 * PublishEmptyTruckActivity
 * 
 * @author larry 2015-4-27 下午2:30:31 
 * @version 1.0.0
 *
 */
public class PublishEmptyTruckActivity extends BaseActivity implements OnClickListener{
	
	private static final int PAGE_SIZE = LContext.PAGE_SIZE;
	private int pageNo = 0;
	
	private Button btnCode;//车牌号码
	private Button btnStart;//当前位置
	
	private Button btnDirect;//流向
	
	private String startCode = LContext.nullStr;
	private String mTruckId = null;
	
	private TruckInfo mInfo;
	
	private List<AreaInfo> mAreas = new ArrayList<AreaInfo>();
	private List<TruckInfo> mList = new ArrayList<TruckInfo>();
	
	private ListViewForScrollView mListView;
	private ExpectedFlowAdapter mAdapter;
	
	private Handler mHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserTruckRequest.PUBLISH_EMPTY_TRUCK_SUCCESSED:
					ProgressDialogHelper.dismiss();
					String description=(String)msg.obj;
					ToastHelper.toastShort(mContext, description);
					new Timer().schedule(new TimerTask() {
						
						@Override
						public void run() {
							setResult(888);
							finish();
						}
					}, 1000);
					break;
				case UserTruckRequest.GET_TRUCK_LIST_SUCCESSED:
					List<TruckInfo> infos = (List<TruckInfo>)msg.obj;
					mList.addAll(infos);
					if(infos.size() > 0){
						mInfo = infos.get(0);
						btnCode.setText(mInfo.getTruckPlateNumber());
						mTruckId = mInfo.getTruckId() + "";
					}else{
						btnCode.setText("您还没有添加车辆,点击添加");
						mInfo = null;
					}
					ProgressDialogHelper.dismiss();
					break;
				case LHttpRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, (String)msg.obj);
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish_empty_truck);
		startService(new Intent(mContext, ShundrService.class));
		btnCode=(Button)findViewById(R.id.btn_code);
		btnStart=(Button)findViewById(R.id.btn_start);
		btnDirect=(Button)findViewById(R.id.btn_truck_direction);
		
		btnCode.setOnClickListener(this);
		
		if(StringUtil.isNull(LContext.mAddress)){
			btnStart.setText("不详");
		}else{
			btnStart.setText(LContext.mAddress);
		}
		
		mListView = (ListViewForScrollView)findViewById(R.id.lv_list);
		mAdapter = new ExpectedFlowAdapter(mContext, mAreas);
		mListView.setAdapter(mAdapter);
		mAdapter.setDeleteListener(new DeleteListener() {
			
			@Override
			public void onDelete(int position) {
				mAreas.remove(position);
				mAdapter.notifyDataSetChanged();
				initButton();
			}
		});
		
		btnDirect.setOnClickListener(this);
		new UserTruckRequest(mContext, mHandler).getTruckList(TruckInfo.TruckStatus.ALL,TruckInfo.TruckValidationStatus.ALL, pageNo, PAGE_SIZE);
	}
	@Override
	public void onClick(View v) {
		Intent start;
		switch (v.getId()) {
		case R.id.btn_code:
			if(mInfo == null){
				startActivityForResult(new Intent(mContext, AddTruckActivity.class), 888);
			}else{
				DialogChoiceTruck truck = new DialogChoiceTruck(mContext, mList, new TruckChoiceListener() {
					
					@Override
					public void onItemClick(TruckInfo info) {
						mInfo = info;
						btnCode.setText(mInfo.getTruckPlateNumber());
						mTruckId = mInfo.getTruckId() + "";
					}
				});
				truck.show(getSupportFragmentManager(), "");
			}
			break;
		case R.id.btn_start:
			start = new Intent(mContext, AreaGridActivity.class);
			start.putExtra("title", "当前位置");
			startActivityForResult(start, 501);
			break;
		case R.id.btn_truck_direction:
			start = new Intent(mContext, AreaGridActivity.class);
			start.putExtra("title", "期望流向");
			startActivityForResult(start, 502);
			break;
		case R.id.btn_save:
			saveTruckInfo();
			break;
		default:
			break;
		}
		
	}
	
	private void saveTruckInfo() {
		try {
			String directStr = "";
			String directCode = "";
			if(mAreas.size() > 0){
				for(AreaInfo info : mAreas){
					directStr = directStr + info.getName() + "-";
					directCode = directCode + info.getCode() + "-";
				}
				directStr = directStr.substring(0, directStr.length() - 1);
				directCode = directCode.substring(0, directCode.length() - 1);
			}
			ProgressDialogHelper.show(mContext, "正在发布空车,请稍后...");
			new UserTruckRequest(mContext, mHandler).publishEmptyTruck(mTruckId, startCode, directStr, directCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initButton(){
		if(mAreas.size() == 4){
			btnDirect.setBackgroundResource(R.drawable.btn_gray_light_selector);
			btnDirect.setClickable(false);
		}else{
			btnDirect.setBackgroundResource(R.drawable.btn_green_light_selector);
			btnDirect.setClickable(true);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		if(requestCode==501){
			if(data != null){
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
					if(areas.size() > 0){
						btnStart.setText(areas.get(0).getName());
						startCode = areas.get(0).getCode();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if(requestCode==502){
			if(data != null){
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
					if(areas.size() > 0){
						if(StringUtil.isNull(areas.get(0).getCode())){
							ToastHelper.toastShort(mContext, "请选择具体城市");
							return ;
						}
						for(AreaInfo info : mAreas){
							if(StringUtil.isEqual(info.getCode(), areas.get(0).getCode())){
								ToastHelper.toastShort(mContext, "该城市已添加,请重新选择");
								return;
							}
						}
					}
					mAreas.addAll(areas);
					mAdapter.notifyDataSetChanged();
					initButton();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if(resultCode == 888){
			new UserTruckRequest(mContext, mHandler).getTruckList(TruckInfo.TruckStatus.ALL,TruckInfo.TruckValidationStatus.ALL, pageNo, PAGE_SIZE);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		menu.getItem(0).setTitle("发布");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			saveTruckInfo();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
